<?php

namespace app\admin\model;

use ba\Random;
use think\Model;
use think\facade\Db;

/**
 * Fields
 */
class Fields extends Model
{
    // 表名
    protected $name = 'fields';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;


    public static function getTimeFormat($key = 'yyyy-mm-dd hh:MM:ss'){
        return [
            'yyyy-mm-dd hh:MM:ss' => 'Y-m-d H:i:s',
            'yyyy-mm-dd hh:MM' => 'Y-m-d H:i',
            'yyyy-mm-dd hh' => 'Y-m-d H',
            'yyyy-mm-dd' => 'Y-m-d',
            'yyyy-mm' => 'Y-m',
            'yyyy' => 'Y'][$key];
    }

    public function getFieldItemAttr($v)
    {
        $v = json_decode($v,true);
        if($v['data']['source'] == 'select'){
            $v['data']['replaceValue']['odds'] = array_map(function($a){ return intval($a);},$v['data']['replaceValue']['odds']);
        }
        return $v;
    }
    public function setFieldItemAttr($v){
        $v = json_encode($v,JSON_UNESCAPED_UNICODE);
        return $v;
    }
  
    /**
     * 生成所有数据
     * @param string $name 表名
     * @param int $number 数量
     * @return bool
     */
    public static function generateDataAll(string $name,int $number = 30){
        if($number <= 0){
            return true;
        }
        $list = [];
        for($i = 0;$i < $number;$i++){
            $datas = self::generateData($name);
           
            $list[] = [
                'datas' => $datas
            ];
        }
        $modelName = 'app\admin\model\\'.ucfirst($name);
        
        return (new $modelName())->saveAll($list);
     
    }
    /**
     * 生成一条数据
     */
    public static function generateData(string $name){
        $list = self::where('name',$name)->select()->toArray();
    
        $data = [];
        $item = [];
        foreach($list as $k => $v){
            
            $value = self::getFieldItemValue($v['field_item']['data'],$v['field_item'],$data,$item);
            if($v['field_item']['data']['source'] == 'starttime'){
                $item['starttime'] = $value;
            }
            if($v['field_item']['data']['source'] == 'endtime'){
                $item['endtime'] = $value;
            }
            $data[$v['field_item']['name']] = $value;
        }
        return $data;
    }
    private static function getFieldItemValue(array $data_source,array $v,array $data,$item):string
    {
        $fun = 'getDataSource'.ucfirst($data_source['source']);
        //判断当前类中是否有某个静态方法
        if(!method_exists(self::class,$fun)){
            return '';
        }
        return self::$fun($data_source,$v,$data,$item);
    }
    private static function getDataSourceMoney(array $data_source,array $v,array $data,array $item){
        $min = $data_source['min'];
        $min = floatval($min);
        $max = $data_source['max'];
        $max = floatval($max);
        $money = rand($min*100,$max*100)/100;
        $money = ceil($money);
        return $money;
    }
    private static function getDataSourceStarttime(array $data_source,array $v,array $data,array $item){
        if(isset($item['endtime'])){
            return $item['endtime'] - rand(600,68400);
        }
        $start = strtotime($data_source['timeRange'][0]);
        $end = strtotime($data_source['timeRange'][1]);
        $time = rand($start,$end);
        return $time;
    }
    private static function getDataSourceEndtime(array $data_source,array $v,array $data,array $item)
    {
        if(isset($item['starttime'])){
            return $item['starttime'] + rand(600,68400);
        }
        $start = strtotime($data_source['timeRange'][0]);
        $end = strtotime($data_source['timeRange'][1]);
        $time = rand($start,$end);
        return $time;
    }
    private static function getDataSourceRandom(array $data_source,array $v,array $data)
    {
        $value = $data_source['randomdata']['value'];
        $list = [];
        if(in_array('username',$value)){
            //生成姓名
            $list[] = self::getRandomUserName(rand(1,10) > 4);
        }
        if(in_array('nickname',$value)){
            $list[] = self::getRandomNickName();
        }
        if(in_array('alpha',$value)){
            if(in_array('number',$value)){
                $list[] = Random::build('alnum',rand(8,20));
            }else{
                $list[] = Random::build('alpha',rand(8,20));
            }
        }else  if(in_array('number',$value)){
            $list[] = Random::build('numeric',rand(8,20));
        }
        if(in_array('chs',$value)){
            //生成随机汉字
            $list[] = self::getRandomChs();
        }
        //打乱数组
        shuffle($list);
        return implode('', $list);
    }
    private static function getRandomChs(){
        $result = '';
        $length = rand(4,8);
        for ($i = 0; $i < $length; $i++) {
            // 常用汉字Unicode范围：0x4E00-0x9FFF（基本汉字区）
            // 0x4E00-0x9FA5 是常用的基本汉字
            $unicode = rand(0x4E00, 0x9FA5);
            
            // 将Unicode转换为UTF-8字符
            $char = mb_convert_encoding(pack('N', $unicode), 'UTF-8', 'UTF-32BE');
            
            // 或者使用更简洁的方法：
            // $char = json_decode('"\u'.sprintf('%04x', $unicode).'"');
            
            $result .= $char;
        }
        
        return $result;
    }
    private static function getRandomNickName(){
        // 中文昵称词库
        $chinese_adjectives = ['阳光', '快乐', '智慧', '勇敢', '温柔', '可爱', '美丽', '帅气', '聪明', 
        '善良', '坚强', '自信', '乐观', '积极', '勤奋', '诚实', '谦虚', '幽默', '优雅', '大方'];
        
        $chinese_animals = ['小猫', '小狗', '小熊', '小兔', '小鹿', '小虎', '小龙', '小鱼', '小鸟', '小马',
         '小牛', '小羊', '小猴', '小鸡', '小鸭', '小鹅', '小象', '小狮', '小豹', '小狼','狗'];
        
        $chinese_nature = ['春风', '夏雨', '秋叶', '冬雪', '晨曦', '晚霞', '星空', '大海', '高山', '流水',
         '白云', '彩虹', '阳光', '月光', '清风', '细雨', '露珠', '花香', '星辰', '银河'];
        
        // 英文昵称词库
        $english_adjectives = ['Happy', 'Sunny', 'Smart', 'Brave', 'Kind', 'Cool', 'Sweet', 'Lovely', 
        'Bright', 'Great', 'Super', 'Magic', 'Dream', 'Star', 'Moon', 'Sun', 'Sky', 'Cloud', 'Rain', 'Wind'];
        
        $english_nouns = ['Cat', 'Dog', 'Bear', 'Rabbit', 'Bird', 'Fish', 'Star', 'Moon', 'Sun',
         'Sky', 'Dream', 'Hope', 'Love', 'Peace', 'Joy', 'Light', 'Wind', 'Rain', 'Cloud', 'Flower'];
        
        // 数字后缀
        $numbers = range(1, 999);
        
        // 随机选择昵称风格
        $style = rand(1, 4);
        
        switch ($style) {
            case 1:
                // 中文形容词+动物+数字
                $adj = $chinese_adjectives[array_rand($chinese_adjectives)];
                $animal = $chinese_animals[array_rand($chinese_animals)];
                $num = array_rand($numbers);
                return $adj . $animal . ($num > 0 ? $num : '');
                
            case 2:
                // 中文自然+数字
                $nature = $chinese_nature[array_rand($chinese_nature)];
                $num = array_rand($numbers);
                return $nature . ($num > 0 ? $num : '');
                
            case 3:
                // 英文形容词+名词+数字
                $adj = $english_adjectives[array_rand($english_adjectives)];
                $noun = $english_nouns[array_rand($english_nouns)];
                $num = array_rand($numbers);
                return $adj . $noun . ($num > 0 ? $num : '');
                
            case 4:
                // 纯中文词语组合
                $adj1 = $chinese_adjectives[array_rand($chinese_adjectives)];
                $adj2 = $chinese_adjectives[array_rand($chinese_adjectives)];
                return $adj1 . $adj2;
        }
    }
    
    private static function getRandomUserName($is_san)
    {
        $lastname_arr  = ['赵','钱','孙','李','周','吴','郑','王','冯','陈','褚','卫','蒋','沈','韩','杨',
        '朱','秦','尤','许','何','吕','施','张','孔','曹','严','华','金','魏','陶','姜',
        '戚','谢','邹','喻','柏','水','窦','章','云','苏','潘','葛','奚','范','彭','郎','鲁','韦',
        '昌','马','苗','凤','花','方','任','袁','柳','鲍','史','唐','费','薛','雷','贺','倪',
        '汤','滕','殷','罗','毕','郝','安','常','傅','卞','齐','元','顾','孟','平','黄','穆','萧',
        '尹','姚','邵','湛','汪','祁','毛','狄','米','伏','成','戴','谈','宋','茅','庞','熊',
        '纪','舒','屈','项','祝','董','梁','杜','阮','蓝','闵','季','贾','路','娄','江','童','颜',
        '郭','梅','盛','林','钟','徐','邱','骆','高','夏','蔡','田','樊','胡','凌','霍','虞',
        '万','支','柯','管','卢','莫','柯','房','裘','缪','解','应','宗','丁','宣','邓','单','杭',
        '洪','包','诸','左','石','崔','吉','龚','程','嵇','邢','裴','陆','荣','翁','荀','于',
        '惠','甄','曲','封','储','仲','伊','宁','仇','甘','武','符','刘','景','詹','龙','叶','幸',
        '司','黎','溥','印','怀','蒲','邰','从','索','赖','卓','屠','池','乔','胥','闻','莘',
        '党','翟','谭','贡','劳','逄','姬','申','扶','堵','冉','宰','雍','桑','寿','通','燕','浦',
        '尚','农','温','别','庄','晏','柴','瞿','阎','连','习','容','向','古','易','廖','庾',
        '终','步','都','耿','满','弘','匡','国','文','寇','广','禄','阙','东','欧','利','师','巩',
        '聂','关','荆','司马','上官','欧阳','夏侯','诸葛','闻人','东方','赫连','皇甫','尉迟',
        '公羊','澹台','公冶','宗政','濮阳','淳于','单于','太叔','申屠','公孙','仲孙','轩辕','令狐',
        '徐离','宇文','长孙','慕容','司徒','司空'];
        $firstname_arr  = ['伟','刚','勇','毅','俊','峰','军','平','保','东','文','辉','力','明',
        '永','健','世','广','志','义','兴','良','海','山','仁','波','宁','贵','福','生','龙',
        '元','全','国','胜','学','祥','才','发','武','新','利','清','飞','彬','富','顺','信','子',
        '杰','涛','昌','成','康','星','光','天','达','安','岩','中','茂','进','林','有','坚',
        '和','彪','博','诚','先','敬','震','振','壮','会','思','群','豪','心','邦','承','乐','绍',
        '功','松','善','厚','庆','磊','民','友','裕','河','哲','江','超','浩','亮','政','谦',
        '亨','奇','固','之','轮','翰','朗','伯','宏','言','若','鸣','朋','斌','梁','栋','维','启',
        '克','伦','翔','旭','鹏','泽','晨','辰','士','以','建','家','致','树','炎','德','行',
        '时','泰','盛','雄','琛','钧','冠','策','腾','楠','榕','风','航','弘','秀','娟','英','华',
        '慧','巧','美','娜','静','淑','惠','珠','翠','雅','芝','玉','萍','红','娥','玲','芬',
        '芳','燕','彩','春','菊','兰','凤','洁','梅','琳','素','云','莲','真','环','雪','荣','爱',
        '妹','霞','香','月','莺','媛','艳','瑞','凡','佳','嘉','琼','勤','珍','贞','莉','桂',
        '娣','叶','璧','璐','娅','琦','晶','妍','茜','秋','珊','莎','锦','黛','青','倩','婷','姣',
        '婉','娴','瑾','颖','露','瑶','怡','婵','雁','蓓','纨','仪','荷','丹','蓉','眉','君',
        '琴','蕊','薇','菁','梦','岚','苑','婕','馨','瑗','琰','韵','融','园','艺','咏','卿','聪',
        '澜','纯','毓','悦','昭','冰','爽','琬','茗','羽','希','欣','飘','育','滢','馥','筠',
        '柔','竹','霭','凝','晓','欢','霄','枫','芸','菲','寒','伊','亚','宜','可','姬','舒','影',
        '荔','枝','丽','阳','妮','宝','贝','初','程','梵','罡','恒','鸿','桦','骅','剑','娇',
        '纪','宽','苛','灵','玛','媚','琪','晴','容','睿','烁','堂','唯','威','韦','雯','苇','萱',
        '阅','彦','宇','雨','洋','忠','宗','曼','紫','逸','贤','蝶','菡','绿','蓝','儿','翠',
        '烟'];
        
        $key1 = rand( 0,count( $lastname_arr )-1 );
        $one_name = $lastname_arr[$key1];

        //获取第二位
        $key2 = rand( 0,count( $firstname_arr )-1 );
        $two_name= $firstname_arr[$key2];
        $three_name = '';
        if($is_san){
            //获取第三位
            $key3 = rand( 0,count( $firstname_arr )-1 );
            $three_name= $firstname_arr[$key3];
        }
        

        $name = $one_name.$two_name.$three_name;

        return $name;
    }
    /**
     * 生成随机手机号
     */
    private static function getDataSourceMobile(array $data_source)
    {
        // 中国移动号段
        $mobilePrefixes = [
            '134', '135', '136', '137', '138', '139', '147', '148',
            '150', '151', '152', '157', '158', '159', '172', '178', '182', '183', '184', '187', '188', '195', '197', '198'
        ];
        
        // 中国联通号段
        $unicomPrefixes = [
            '130', '131', '132', '145', '146', '155', '156', '166', '167', '171', '175', '176', '185', '186', '196'
        ];
        
        // 中国电信号段
        $telecomPrefixes = [
            '133', '149', '153', '173', '174', '177', '180', '181', '189', '190', '191', '193', '199'
        ];
        
        // 虚拟运营商号段
        $virtualPrefixes = [
            '162', '165', '167', '170', '171'
        ];
        
        // 合并所有号段
        $allPrefixes = array_merge($mobilePrefixes, $unicomPrefixes, $telecomPrefixes, $virtualPrefixes);
        
        // 随机选择一个号段
        $prefix = $allPrefixes[array_rand($allPrefixes)];
        
        // 生成后8位随机数字
        $suffix = '';
        for ($i = 0; $i < 8; $i++) {
            $suffix .= rand(0, 9);
        }
        
        return $prefix . $suffix;
    }
    /**
     * 生成随机车牌号
     */
    private static function getDataSourceCar(array $data_source){
        // $prefix = $data_source['prefix'] ?? '';

        $suffix = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 
        'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        //车牌号数字一般多些，这里多写了一个数字
        $number = array_merge(
            [0,1,2,3,4,5,6,7,8,9],
            [0,1,2,3,4,5,6,7,8,9],
            $suffix,
            [0,1,2,3,4,5,6,7,8,9],
            [0,1,2,3,4,5,6,7,8,9],
            [0,1,2,3,4,5,6,7,8,9],
            [0,1,2,3,4,5,6,7,8,9],
            [0,1,2,3,4,5,6,7,8,9],
            [0,1,2,3,4,5,6,7,8,9],
        );
        $cont = count($number) - 1;
        // 随机选择车牌类型：50%概率新能源车牌，50%概率燃油车牌
        $isNewEnergy = rand(0, 1) === 1;
        if($isNewEnergy){
            $typeLetter = ['A','B','C','D','E','F','G','H'][rand(0, 7)]; // D代表纯电动，F代表插电混动
            $car = '川' .['A','A','A','G','G'][rand(0,4)]. $typeLetter . 
            $number[rand(0,$cont)] . 
            '**'.
            $number[rand(0,$cont)] .
            $number[rand(0,$cont)];
        }else{
            $car = '川' . ['A','A','A','G','G'][rand(0,4)] . 
            $number[rand(0,$cont)] . 
            '**' .
            $number[rand(0,$cont)] .
            $number[rand(0,$cont)];
        }
        return $car;
    }
    /**
     * 生成随机IP地址
     */
    private static function getDataSourceIp(array $data_source){
        // 中国IP地址段（主要运营商分配的IP段）
        $chinaIpRanges = [
            // 中国电信
            ['1.0.1.0', '1.0.3.255'],
            ['1.1.0.0', '1.1.8.255'],
            ['1.2.0.0', '1.2.7.255'],
            ['1.4.1.0', '1.4.7.255'],
            ['1.10.0.0', '1.10.15.255'],
            ['14.0.0.0', '14.255.255.255'],
            ['27.0.0.0', '27.255.255.255'],
            ['36.0.0.0', '36.255.255.255'],
            ['39.0.0.0', '39.255.255.255'],
            ['42.0.0.0', '42.255.255.255'],
            ['49.0.0.0', '49.255.255.255'],
            ['58.0.0.0', '58.255.255.255'],
            ['59.0.0.0', '59.255.255.255'],
            ['60.0.0.0', '60.255.255.255'],
            ['61.0.0.0', '61.255.255.255'],
            ['101.0.0.0', '101.255.255.255'],
            ['106.0.0.0', '106.255.255.255'],
            ['110.0.0.0', '110.255.255.255'],
            ['111.0.0.0', '111.255.255.255'],
            ['112.0.0.0', '112.255.255.255'],
            ['113.0.0.0', '113.255.255.255'],
            ['114.0.0.0', '114.255.255.255'],
            ['115.0.0.0', '115.255.255.255'],
            ['116.0.0.0', '116.255.255.255'],
            ['117.0.0.0', '117.255.255.255'],
            ['118.0.0.0', '118.255.255.255'],
            ['119.0.0.0', '119.255.255.255'],
            ['120.0.0.0', '120.255.255.255'],
            ['121.0.0.0', '121.255.255.255'],
            ['122.0.0.0', '122.255.255.255'],
            ['123.0.0.0', '123.255.255.255'],
            ['124.0.0.0', '124.255.255.255'],
            ['125.0.0.0', '125.255.255.255'],
            ['171.0.0.0', '171.255.255.255'],
            ['175.0.0.0', '175.255.255.255'],
            ['180.0.0.0', '180.255.255.255'],
            ['182.0.0.0', '182.255.255.255'],
            ['183.0.0.0', '183.255.255.255'],
            ['202.0.0.0', '202.255.255.255'],
            ['203.0.0.0', '203.255.255.255'],
            ['210.0.0.0', '210.255.255.255'],
            ['211.0.0.0', '211.255.255.255'],
            ['218.0.0.0', '218.255.255.255'],
            ['219.0.0.0', '219.255.255.255'],
            ['220.0.0.0', '220.255.255.255'],
            ['221.0.0.0', '221.255.255.255'],
            ['222.0.0.0', '222.255.255.255'],
            ['223.0.0.0', '223.255.255.255']
        ];
        
        // 随机选择一个中国IP段
        $range = $chinaIpRanges[array_rand($chinaIpRanges)];
        $start = ip2long($range[0]);
        $end = ip2long($range[1]);
        
        // 生成随机IP
        $randomIp = rand($start, $end);
        
        // 转换为IP地址格式
        return long2ip($randomIp);
    }
    private static function getDataSourceSelect(array $data_source){
        $probabilities = $data_source['replaceValue']['odds'];
        if(empty($probabilities)){
            return '';
        }
        // 计算总权重
        $totalWeight = array_sum($probabilities);
        
        // 如果总权重为0，随机返回一个下标
        if ($totalWeight <= 0) {
            return '';
        }
        // 生成随机数
        $random = rand(1, $totalWeight);
        
        // 累积权重
        $cumulativeWeight = 0;
        
        foreach ($probabilities as $index => $weight) {
            $cumulativeWeight += $weight;
            if ($random <= $cumulativeWeight) {
                return $index;
            }
        }
        return '';
    }
    /**
     * 获取数据仓库数据
     */
    private static function getDataSourceStore(array $data_source){
        $info = Store::where('name',$data_source['source_field'])->orderRaw('RAND()')->field('full_name')->find();
        return $info['full_name'] ?? '';
    }

}